<template>
  <el-dialog v-model="showDialog"
             :title="title"
             :width="width"
             :destroy-on-close="true"
             :show-close="false"
             :close-on-click-modal="false"
             :draggable="true"
  >
    <template #title>
      <slot name="header">
        {{ title }}
      </slot>
    </template>
    <el-form :model="forgetFormItem"
             ref="forgetFormRef"
             :rules="forgetFormRules"
             status-icon>
      <el-form-item prop="email">
        <el-input v-model="forgetFormItem.email" placeholder="请输入邮箱" type="text">
          <template #prefix>
            <el-icon>
              <Message/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="forgetFormItem.password" placeholder="请输入密码" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Unlock/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="checkPassword">
        <el-input v-model="forgetFormItem.checkPassword" placeholder="请确认密码" type="password" show-password>
          <template #prefix>
            <el-icon>
              <Unlock/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="verificationCode">
        <el-input v-model="forgetFormItem.verificationCode"
                  :placeholder="forgetFormItem.verificationCodeShow"
                  type="text" style="width: 50%"/>
        <el-button type="primary" style="width: 50%;"
                   :disabled="forgetFormItem.isCount"
                   @click="passwordEmailFn">
          {{ forgetFormItem.verificationButton }}
        </el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="showCancel" @click="cancel(forgetFormRef)">{{ cancelText }}</el-button>
        <el-button type="primary" @click="confirm(forgetFormRef)" :loading="forgetFormItem.okLoading">{{ confirmText }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {onUnmounted, reactive, ref, watch} from "vue";
import type {FormInstance, FormRules} from "element-plus";
import {email_reg} from "@/constants/format-constant.ts";
import {Unlock, Message} from "@element-plus/icons-vue"
import {
  verification_default_text,
  verification_time,
  verification_type_email
} from "@/constants/verification-constant.ts";
import {forgetReq, passwordEmailReq} from "@/api/login/login.ts";
import {elMessageTip, errorMessageTip} from "@/utils/tip-utils.ts";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {forget_email_param_key, forget_email_param_tag} from "@/constants/param-constant.ts";
import {getParamValueUtil} from '@/utils/common-request.ts'

interface ForgetFormItem {
  email: string;
  password: string;
  checkPassword: string;
  verificationButton: string;
  verificationCount: number;
  verificationCodeShow: string;
  isCount: boolean;
  verificationCode: string;
  redisKey: string;
  okLoading: boolean;
}

const forgetFormItem = reactive<ForgetFormItem>({
  email: '',
  password: '',
  checkPassword: '',
  verificationButton: verification_default_text,
  verificationCount: verification_time,
  verificationCodeShow: '填写验证码',
  isCount: false,
  verificationCode: '',
  redisKey: '',
  okLoading: false,
})

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '弹窗'
  },
  width: {
    type: String,
    default: '30%'
  },
  showCancel: {
    type: Boolean,
    default: true
  },
  cancelText: {
    type: String,
    default: '取消'
  },
  confirmText: {
    type: String,
    default: '确定'
  }
})

const forgetFormRef = ref<FormInstance>()

const forgetFormRules = reactive<FormRules<ForgetFormItem>>({
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {pattern: email_reg, message: '邮箱格式不正确', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  checkPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  verificationCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
  ]
})

const emit = defineEmits(['update:showDialog', 'confirm', 'cancel'])

// 内部维护的可见性状态（解决直接修改prop的问题）
let showDialog = ref(props.showDialog)

// 监听外部传入的modelValue变化
watch(() => props.showDialog, val => {
  showDialog.value = val
})

// 确认按钮点击
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      updatePassword(formEl)
    } else {
      errorMessageTip('请填写完整信息')
    }
  })
}

const updatePassword = async (formEl: FormInstance | undefined) =>{
  forgetFormItem.okLoading = true
  const params = {
    email: forgetFormItem.email,
    password: forgetFormItem.password,
    checkPassword: forgetFormItem.checkPassword,
    verificationBean: {
      verificationCode: forgetFormItem.verificationCode,
      redisKey: forgetFormItem.redisKey,
      checkType: verification_type_email
    }
  }
  const res: any = await forgetReq(params);
  forgetFormItem.okLoading = false
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS) {
    showDialog.value = false
    close(formEl)
  }
}

// 取消按钮点击
const cancel = (formEl: FormInstance | undefined) => {
  close(formEl)
}

// 关闭弹窗（不触发事件）
const close = (formEl: FormInstance | undefined) => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  initComponents()
  showDialog.value = false
  resetForm(formEl)
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 初始化控件
const initComponents = () => {
  forgetFormItem.isCount = false
  forgetFormItem.verificationButton = verification_default_text
  forgetFormItem.verificationCodeShow = '填写验证码'
  forgetFormItem.verificationCode = ''
  forgetFormItem.redisKey = ''
  forgetFormItem.okLoading = false
}

// 发送验证码
const passwordEmailFn = async () => {
  const param = {
    email: forgetFormItem.email
  }
  const res: any = await passwordEmailReq(param)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS) {
    const verificationCodeLength = getParamValueUtil(forget_email_param_tag, forget_email_param_key);
    forgetFormItem.verificationCodeShow = '标识码:' + res.data.substring(0, verificationCodeLength);
    forgetFormItem.redisKey = res.data;
    countDown();
  }
}

// 倒计时
let timer: number | null = null;

const countDown = () => {
  let count = forgetFormItem.verificationCount
  forgetFormItem.verificationButton = count + '秒后重试'
  forgetFormItem.isCount = true
  // 清除之前的定时器
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  timer = window.setInterval(() => {  // 使用 window.setInterval
    if (count == 0) {
      forgetFormItem.verificationButton = verification_default_text
      forgetFormItem.isCount = false
      if (timer) {
        clearInterval(timer)
        timer = null
      }
    } else {
      forgetFormItem.verificationButton = count + '秒后重试'
      count--
    }
  }, 1000)
}

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
    forgetFormItem.isCount = false
    forgetFormItem.verificationButton = verification_default_text
  }
})

</script>

<style scoped>

</style>